package com.lujianfei.powersearch.utils;

import android.content.Context;
import android.net.Uri;

import com.lujianfei.powersearch.logger.LoggerFactory;
import com.lujianfei.powersearch.ui.createOrUpdate.widget.imageviewedit.model.ImageViewEditItem;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;

/**
 * 描述:
 * 创建者: lujianfei
 * 日期: 2025/10/10
 */

public class ImageUtils {

    public static ImageViewEditItem getImageByPath(String path) {
        boolean isPath = path.contains("image_");
        Uri imageUri = !isPath? Uri.parse(path) : null;
        String imageUrl = isPath? path : null;
        return new ImageViewEditItem(imageUri, imageUrl, ImageViewEditItem.TYPE_NORMAL);
    }

    public static String copyUriToInternalStorage(Context context, Uri uri) {
        if (uri.toString().contains("video")) {
            return uri.toString();
        }
        String fileName = "image_" + System.currentTimeMillis() + ".jpg";
        try (InputStream in = context.getContentResolver().openInputStream(uri);
            OutputStream out = Files.newOutputStream(new File(context.getFilesDir(), fileName).toPath())) {
            byte[] buffer = new byte[4096];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            String finalPath = new File(context.getFilesDir(), fileName).getAbsolutePath();
            LoggerFactory.getLogger().d("ImageUtils", "Image copied to: " + finalPath);
            return finalPath;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
